import ast
import os.path

import requests
from lxml import etree

from config import HEADERS
from detect import detect_dangercalls


def get_module(path):
    dirname, filename = os.path.split(path)  # dirname为目录名，filename为文件名
    fname, fename = os.path.splitext(filename)  # fname为不带文件后缀名的文件名，fename为文件后缀名
    front_name = dirname
    while front_name != '' and front_name != '/':
        dirs = os.listdir(front_name)
        if '__init__.py' in dirs:  # 如果目录中存在"__init__.py"文件
            front_name, back_name = os.path.split(front_name)  # back_name为有"__init__.py"的目录名
            fname = back_name + '.' + fname  # 添加带有"__init__.py"的目录名
        else:
            break
    return fname


# print(get_module('../test/multiple_packages/requests-2.27.1/tests/testserver/server.py'))


def get_complete_name(func, aliases):
    if isinstance(func, ast.Name):
        # 如果函数前不存在模块名
        if func.id in aliases:
            # 如果该函数使用as进行改名
            return aliases[func.id]
        return func.id
    elif isinstance(func, ast.Attribute):
        # 如果函数前存在模块名
        pre_name = get_complete_name(func.value, aliases)  # 获取改名前的模块名
        back_name = func.attr
        name = pre_name + '.' + back_name
        if name in aliases:
            # 如果使用as进行改名
            return aliases[name]
        return name
    else:
        return ''


def get_call_name(node, aliases):
    if isinstance(node.func, ast.Name):
        # 如果函数前不存在模块名
        if getattr(node.func, 'id') in aliases:
            # 如果该函数使用as进行改名
            return aliases[getattr(node.func, 'id')]
        return getattr(node.func, 'id')
    elif isinstance(node.func, ast.Attribute):
        # 如果函数前存在模块名
        return get_complete_name(node.func, aliases)
    else:
        return ''


def get_request(url):
    response = requests.get(url=url, headers=HEADERS)
    # print(response.text)
    return response


def get_version(text):
    html = etree.HTML(text)
    version = html.xpath('/html/body/div[2]/div[2]/div[1]/table/tr[1]/td[1]/a/text()')
    return version[0]


def get_pypi_homepage_url(text):
    html = etree.HTML(text)
    # href = html.xpath('/html/body/div[2]/div[2]/div[1]/p[2]/span[3]/a/@href')
    hrefs = html.xpath('/html/body/div[2]/div[2]/div[1]/p[2]/span/a/@href')
    for href in hrefs:
        if 'pypi.org' in href:
            return href
    return ''


def get_repository_url(text):
    html = etree.HTML(text)
    href = html.xpath('/html/body/div[2]/div[2]/div[1]/p[2]/span[2]/a/@href')
    return href[0]


def get_pypi_package_url(text):
    html = etree.HTML(text)
    href = html.xpath('//*[@id="files"]/div[1]/div[2]/a[1]/@href')
    file_name = html.xpath('//*[@id="files"]/div[1]/div[2]/a[1]/text()')
    file_name = file_name[0].strip()
    if not href:
        return '', ''
    href = href[0]
    if not href.endswith('.tar.gz') and not href.endswith('.zip'):
        return '', ''
    return href, file_name


def get_zipped_py_files(members):
    for tarinfo in members:
        if os.path.splitext(tarinfo.name)[1] == ".py":
            yield tarinfo
